/**
 *   @description 接口请求拦截
 *   @author Xiaohui Zeng
 *   @date 2019/11/29
 */
import {apiUrl} from '@/config/config'
import axios from 'axios'
import {Message} from 'view-design'
import router from '@/router'

export const baseUrl = (process.env.NODE_ENV === 'development' ? apiUrl.dev : apiUrl.pro) + 'admin/'
export const TOKEN_KEY = 'ApiAdmin_'

export const setToken = (token) => {
    sessionStorage.setItem(TOKEN_KEY + 'ApiAuth', token)
}

export const getToken = () => {
    const token = sessionStorage.getItem(TOKEN_KEY + 'ApiAuth')
    if (token) {
        return token
    } else {
        return false
    }
}

class HttpRequest {
    constructor(baseUrl) {
        this.baseUrl = baseUrl
    }

    interceptors(instance) {
        // 请求拦截
        instance.interceptors.request.use(config => {
            return config
        }, error => {
            return Promise.reject(error)
        })
        // 响应拦截
        instance.interceptors.response.use(res => {
            // console.log(res)
            const {data, status} = res
            if (data.code < 0) {
                if (data.code === -14) {
                    setToken('')
                    Message.warning('登录已过期，请重新登录！')
                    router.push({name: 'login'})
                } else {
                    Message.error(data.msg)
                }
                throw new Error(data.msg)
            } else {
                return {data, status}
            }
        }, error => {
            return Promise.reject(error)
        })
    }

    request(options) {
        const instance = axios.create()
        let apiAuth = getToken()
        if (apiAuth === false) {
            options = Object.assign({
                baseURL: this.baseUrl,
                headers: {}
            }, options)
        } else {
            options = Object.assign({
                baseURL: this.baseUrl,
                headers: {
                    apiAuth: apiAuth
                }
            }, options)
        }
        this.interceptors(instance)
        return instance(options)
    }
}

const api_axios = new HttpRequest(baseUrl)
export default api_axios
